package wangxiaotao.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import wangxiaotao.common.CommonResult;
import wangxiaotao.converter.OrderConverter;
import wangxiaotao.entity.Order;
import wangxiaotao.entity.User;

import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController extends BaseController{
    private final OrderConverter orderConverter;

    @RequiresAuthentication
    @GetMapping("/listUserOrder/{userId}")
    public CommonResult getAllOrder(String type, String data, @PathVariable Integer userId){
        Assert.notNull(userId,"用户id不能为空");
        QueryWrapper<Order> wrapper = new QueryWrapper<Order>().like(StrUtil.isNotBlank(type), type, data);
        wrapper.eq("user_id",userId);
        return CommonResult.success(orderService.page(getPage(), wrapper));
    }

    @RequiresAuthentication
    @GetMapping("/order/delete/{userId}")
    public CommonResult deleteUserOrder(Integer orderId, @PathVariable String userId){
        Assert.notNull(orderId,"订单id不能为空");
        Assert.notNull(userId,"用户id不能为空");
        if (orderService.removeById(orderId))
            return CommonResult.success();
        return CommonResult.fail();
    }

    @RequiresAuthentication
    @GetMapping("/order")
    public CommonResult getOrderByOrderId(Integer orderId,Integer userId){
        Assert.notNull(orderId,"订单id不能为空");
        Assert.notNull(userId,"用户id不能为空");
        Order order = orderService.getOne(new QueryWrapper<Order>()
                        .eq("user_id",userId)
                        .eq("id", orderId));
        return CommonResult.success(orderConverter.toUserOrderVO(order));
    }

    @RequiresAuthentication
    @PostMapping("/updateUser/{userId}")
    public CommonResult updateUserOrder(@RequestBody Map<String,Object> req, @PathVariable Integer userId){
        String type = (String)req.get("type");
        Object value = req.get("value");
        Assert.notNull(userId,"用户id不能为空");
        Assert.notNull(type,"修改类型不能为空");
        Assert.notNull(value,"修改数据不能为空");
        if (userService.update(new UpdateWrapper<User>().set(type,value).eq("id",userId)))
            return CommonResult.success();
        return CommonResult.fail();
    }
}
